﻿var MCP = MCP || {};

function Check() {
	this.TotalPrice = 0;
	this.ShopName = '';
	this.Items = new Array();

	this.AddNewItem = function(item) {
		this.Items.push(item);
	};
	
	this.Compose = function () {
		this.TotalPrice = parseFloat($('#total-price-field').val());
		this.ShopName = $('#shop-name-field').val();
		//addItem();
		return this;
	};
}

function Item() {
	this.Name = '';
	this.Amount = 0;
	this.UnitPrice = 0;
	this.Price = 0;
	this.Categories = '';

	this.Compose = function () {
		this.Name = $("#new-item-Name").val();
		this.Amount = MCP.Helper.ParseFloatValue("#new-item-Amount");
		this.UnitPrice = MCP.Helper.ParseFloatValue("#new-item-UnitPrice");
		this.Price = MCP.Helper.ParseFloatValue("#new-item-Price");
		this.Categories = $('#category-tag').tagit('assignedTags');
		return this;
	};
	
	this.ClearItem = function () {
		$("#new-item-Name").val("");
		$("#new-item-Amount").val("");
		$("#new-item-UnitPrice").val("");
		$("#new-item-Price").val("");
		$('#category-tag').tagit("removeAll");

		this.Name = '';
		this.Amount = 0;
		this.UnitPrice = 0;
		this.Price = 0;
		this.Categories = '';
	};

	this.IsEmpty = function() {
		if ($("#new-item-Name").val() == '' &&
			$("#new-item-Amount").val() == '' &&
			$("#new-item-UnitPrice").val() == '' &&
			$("#new-item-Price").val() == '') {
			return true;
		} else {
			return false;
		}
	};

	this.Autocomplete = function() {

	};
}

MCP.ChecksHandler = MCP.ChecksHandler || (function () {
    var check = new Check();
    var checksItems = new Array();
	var item = new Item();
    var categories = new Array();
    //var itemCategories = new Array();

    var init = function () {
        //var mask = '<div class="check-item">${Name} ${Amount} * ${UnitPrice} = ${Price}</div>';
        //$.template("itemsTemplate", mask);
    };

    //var composeItem = function () {
    //    item =
    //        {
    //            Name: $("#new-item-Name").val(),
    //            Amount: parseFloatValue("#new-item-Amount"),
    //            UnitPrice: parseFloatValue("#new-item-UnitPrice"),
    //            Price: parseFloatValue("#new-item-Price"),
    //            Categories: $('#category-tag').tagit('assignedTags')
    //        };
    //};

    var addItem = function () {
        // TODO: replace with validation!
        if ($("#new-item-Name").val()
            && $("#new-item-Amount").val()
            && $("#new-item-UnitPrice").val()
            && $("#new-item-Price").val()) {
	        item.Compose();

	        var itemCopy = MCP.Helper.Copy(item);
            check.AddNewItem(itemCopy);
            item.ClearItem();

            templateItems();
        }
    };

    //var addCategoryForItem = function (choosedCategory) {
    //    var categoryIndex = $.inArray(choosedCategory, $.Enumerable.From(categories).Select(function (i) { return i.name; }));
    //    if (categoryIndex >= 0) {
    //        var category = categories[categoryIndex];
    //        itemCategories.push({ ID: category.ID, Name: category.Name });
    //    } else {
    //        itemCategories.push({ ID: null, Name: choosedCategory });
    //    }
    //};

    var saveCheck = function () {
	    if (!item.IsEmpty) {
		    addItem();
	    }
	    
        var dataJSON = JSON.stringify(check.Compose());

        $.ajax(
            {
                url: '/ChecksList/AddNewCheck',
                data: dataJSON,
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    //$.get("/ChecksList/ChecksList");
                    window.location = "/ChecksList/ChecksList";
                },
                error: function (data) {
                    alert('Error!');
                }
            });
    };

    //var clearItem = function () {
    //    $("#new-item-Name").val("");
    //    $("#new-item-Amount").val("");
    //    $("#new-item-UnitPrice").val("");
    //    $("#new-item-Price").val("");
    //    $("#categories-autocomplete").val();

    //    item.Name = '';
    //    item.Amount = 0;
    //    item.UnitPrice = 0;
    //    item.Price = 0;
    //};

    //var getCheck = function () {
    //    check.TotalPrice = parseFloat($('#total-price-field').val());
    //    check.ShopName = $('#shop-name-field').val();
    //    addItem();
    //    check.Items = checksItems;
    //    return check;
    //};

    var addNewItemClick = function () {
    	$("div#new-check-area").slideToggle("slow");
        $(this).toggleClass("active");

        //$("a#addNewItem_Apply")
	    //    .unbind('click')
	    //    .click(function () {
		//		MCP.ChecksHandler.AddItem();
        //});
        //$("a#addNewItem_Cancel")
	    //    .unbind('click')
	    //    .click(function () {
		//		MCP.ChecksHandler.ClearItem();
        //});
    };

    var templateItems = function () {
        var mask = '<div class="check-item">{Name} {Amount} * {UnitPrice} = {Price}</div>';
        $("#itemsList").html('');
        var container = $("#itemsList");

        $.each(checksItems, function (i, currentItem) {
            container.append($.nano(mask, currentItem));
        });
    };

    //var copy = function (obj) {
    //    // (c) OWL JavaScript Utilities
    //    // Oran Looney, April 2008

    //    if (typeof obj !== 'object') {
    //        return obj;
    //    } else {
    //        var value = obj.valueOf();
    //        if (obj != value) {
    //            return new obj.constructor(value);
    //        } else {
    //            if (obj instanceof obj.constructor && obj.constructor !== Object) {
    //                var c = clone(obj.constructor.prototype);

    //                for (var property in obj) {
    //                    if (obj.hasOwnProperty(property)) {
    //                        c[property] = obj[property];
    //                    }
    //                }
    //            } else {
    //                var c = {};
    //                for (var property in obj) c[property] = obj[property];
    //            }

    //            return c;
    //        }
    //    }
    //};

    //var parseFloatValue = function (selectorID) {
    //    return parseFloat($(selectorID).val().replace(',', '.'));
    //};

    var clearItem = function() {
        item.ClearItem();
    };

    $.nano = function (template, data) {
        return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
            var keys = key.split("."), value = data[keys.shift()];
            $.each(keys, function () { value = value[this]; });
            return (value === null || value === undefined) ? "" : value;
        });
    };

    return {
    	Initialize: init
    	, AddNewItemClick: addNewItemClick
    	//, Check: getCheck()
    	//, Items: checksItems
    	, AddItem: addItem
    	//, ClearItem: clearItem
    	//, TemplateItems: templateItems
    	, SaveCheck: saveCheck
    	//, Categories: categories
        //, ParseFloatValue: parseFloatValue
    	, ClearItem: clearItem
    	, Check : check
    };
})()